<?php
/*
PWision extension: Newspaper http://pw-newspaper.googlecode.com/
Copyright (C) 2012-3 Becheru Petru-Ioan

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

include_once("inc/PTable.inc");
include_once("inc/PFormSection.inc");
include_once("inc/Users.inc");
include_once('inc/BBCode.inc');


/** 	The Feed class is designed to model an Atom feed.
	*	\latexonly  \label{PWision:Extensions:Newspaper:Feed} \index{extension} \index{Atom}\endlatexonly
	*	\brief an Atom feed section.
	*	\version 1.0.1
	*/
class Feed extends PSection
	{
/*	function setParams()
		{
		parent::setParams();
		$this
			->addParam('Nume',"/^[ a-z#&0-9;șțîâȘȚÎÂăĂ-]{0,256}$/i",'')
			;
		}
	protected function preprocessParam($param_name)
		{
// 		$_REQUEST[$param_name]=charset_decode_utf_8($_REQUEST[$param_name]);
		$_REQUEST[$param_name]=str_replace('&#160;',' ',$_REQUEST[$param_name]);// nbsp as a special char not allowed. fix for a chromium bug
		$_REQUEST[$param_name]=str_replace('ş','ș',$_REQUEST[$param_name]);
		$_REQUEST[$param_name]=str_replace('Ş','Ș',$_REQUEST[$param_name]);
		$_REQUEST[$param_name]=str_replace('ţ','ț',$_REQUEST[$param_name]);
		$_REQUEST[$param_name]=str_replace('Ţ','Ț',$_REQUEST[$param_name]);
		}*/
	function if_parameters_are_set()
		{
		parent::if_parameters_are_set();
		}
	function if_not_all_parameters_are_set()
		{
		parent::if_not_all_parameters_are_set();
		$this->if_parameters_are_set();
		}

	function	Chapter1()
		{
		$ret=new PContent();
		$feed=El('feed')
				->setAtr('xmlns','http://www.w3.org/2005/Atom')
			->Insert(
				El('title')
					->Insert(new PText(xmlentities(
						html_entity_decode(Main()->getTitle(),ENT_QUOTES,'UTF-8')
						)))
				)
			->Insert(
				El('subtitle')
					->Insert(new PText(xmlentities(
						html_entity_decode(Main()->getMotto(),ENT_QUOTES,'UTF-8')
						)))
				)
			->Insert(
				Object(new PSimpleTag('link'))
					->setAtr('href','http'.(isset($_SERVER['HTTPS'])?'s':'').'://'.$_SERVER['SERVER_NAME'].'/Feed')
					->setAtr('rel','self')
				)
			->Insert(
				Object(new PSimpleTag('link'))
					->setAtr('href','http'.(isset($_SERVER['HTTPS'])?'s':'').'://'.$_SERVER['SERVER_NAME'])
					->setAtr('hreflang',Main()->getLanguage())
				)
			->Insert(
				El('id')
					->Insert(new PText(
						'http'.(isset($_SERVER['HTTPS'])?'s':'').'://'.$_SERVER['SERVER_NAME']
						))
				)
			->Insert(
				El('author')
					->Insert(
						El('name')
							->Insert(new PText(xmlentities(
								html_entity_decode(Main()->getTitle(),ENT_QUOTES,'UTF-8')
								)))
						)
				)
			->Insert(
				El('logo')
					->Insert(new PText('/css/images/logo1.png'))
				)
			;
		$keywords=explode(',', Main()->getKeywords());
		if(count($keywords))foreach($keywords as $keyword)
			if($keyword=trim($keyword))
			$feed->Insert(
				Object(new PSimpleTag('category'))
					->setAtr('term',xmlentities(html_entity_decode($keyword,ENT_QUOTES,'UTF-8')))
				);
		$arts=Main()->DB->fetch_all_query(
"
SELECT DISTINCT MAX( logs.TValue )  `Mod` , sub_articles.TValue `Title` , NArticle. * 
FROM NArticleTag `sub_articles` , NArticleTag `logs` , NArticle
WHERE sub_articles.IDTag =1
AND logs.IDArticle = sub_articles.IDArticle
AND logs.IDTag =9
AND NArticle.ID = sub_articles.IDArticle
GROUP BY  `ID` ,  `Title` 
ORDER BY  `Mod` DESC , Volume +0 DESC , Issue +0 DESC , firstPage +0 ASC , lastPage +0 ASC ,  `ID` ASC 
LIMIT 0 , 20"
			);
		if(count($arts))
		{
		$updated=Feed::log2AtomTime($arts[0]['Mod']);
			$feed
				->Insert(
					El('updated')
						->Insert(new PText(
							$updated
							))
					);
		foreach($arts as &$art)
			{
			$art_URL='http'.(isset($_SERVER['HTTPS'])?'s':'').'://'.$_SERVER['SERVER_NAME'].'/('.$art['ID'].')';
			$updated=Feed::log2AtomTime($art['Mod']);
			$entry=El('entry')
				->Insert(
					El('title')
// 							->setAtr('lang',$art['Language'])
						->Insert(new PText(xmlentities(
							html_entity_decode($art['Title'],ENT_QUOTES,'UTF-8')
							)))
					)
// 				->Insert(
// 					El('subtitle')
// 							->setAtr('lang',$art['absLanguage'])
// 						->Insert(new PText(xmlentities(
// 							$art['abstractTitle']
// 							)))
// 					)
				->Insert(
					El('id')
						->Insert(new PText($art_URL))
					)
				->Insert(
					El('updated')
						->Insert(new PText(
							$updated
							))
					)
				->Insert(
					El('summary')
// 							->setAtr('lang',$art['absLanguage'])
							->setAtr('type','xhtml')
						->Insert(
							El('div')
									->setAtr('xmlns','http://www.w3.org/1999/xhtml')
								->Insert(new PText(
									($art['coverURL']?"<img src='{$art['coverURL']}' width='300px'/>":'').
									html_entity_decode(xmlentities($art['textAbstract']),ENT_QUOTES,'UTF-8')
									))
							)
					)
				->Insert(
					El('content')
							->setAtr('src',$art_URL)
// 							->setAtr('srclang',$art['Language'])
					)
				->Insert(
					Object(new PSimpleTag('link'))
						->setAtr('href',$art_URL)
						->setAtr('hreflang',$art['Language'])
					)
				;
			if($art['pdfURL'])
			$entry
				->Insert(
					Object(new PSimpleTag('link'))
						->setAtr('type','application/pdf')
						->setAtr('href',$art['pdfURL'])
						->setAtr('hreflang',$art['Language'])
						->setAtr('rel','alternate')
					)
				;
				
			$art['Authors']=array_column( Main()->DB->fetch_all_query('select TValue from NArticleTag where IDArticle='.$art['ID'].' and IDTag=3 order by ID'), 'TValue' );
			if(count($art['Authors']))foreach($art['Authors'] as $author)
				{
				$entry->Insert(
					El('author')
						->Insert(
							El('name')
								->Insert(new PText(
									html_entity_decode(xmlentities($author),ENT_QUOTES,'UTF-8')
									))
							)
					);
				}
				
			$art['keywords']=array_column( Main()->DB->fetch_all_query('select TValue from NArticleTag where IDArticle='.$art['ID'].' and IDTag=4 order by ID'), 'TValue' );
			if(count($art['keywords']))foreach($art['keywords'] as $keyword)
				{
				$entry->Insert(
					Object(new PSimpleTag('category'))
						->setAtr('term',xmlentities(html_entity_decode($keyword,ENT_QUOTES,'UTF-8')))
					);
				}

			
			$feed->Insert($entry);
			}
		}
		$ret->Insert($feed);
		return $ret;
		}
	/**	This function transform an date time from the log to Atom time;
		*	\brief log to Atom time
		*	\version 1.0.1
		*	\param $log 2012-12-13 01:41:59 
		* \return 2012-12-13T01:41:59Z
		*/
	static private function log2AtomTime($log)
		{
		preg_match('`^\s*(?<An>[0-9]{4})-(?<Luna>[0-9]{2})-(?<Zi>[0-9]{2})\s*((?<Ora>[0-9]{2}):(?<Minut>[0-9]{2}):(?<Secunda>[0-9]{2}))?`',$log,$matches);
		$AtomTime='';
		$AtomTime .= isset($matches['An'])?$matches['An']:date('Y');
		$AtomTime .= '-'.(isset($matches['Luna'])?$matches['Luna']:'01');
		$AtomTime .= '-'.(isset($matches['Zi'])?$matches['Zi']:'01');
		$AtomTime .= 'T'.(isset($matches['Ora'])?$matches['Ora']:'00');
		$AtomTime .= ':'.(isset($matches['Minut'])?$matches['Minut']:'00');
		$AtomTime .= ':'.(isset($matches['Secunda'])?$matches['Secunda']:'00');
		$AtomTime .= 'Z';
		return $AtomTime;
		}
	}
?>